import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStoreHook } from "@/store/modules/user";
import { useUserStore } from "@/store/modules/user";
import moment from "moment";

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});
// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
      if (config.url == "/api/v1/auth/refresh_token") return config;
      if (userStore.tokenExpire - new Date().getTime() <= 1000 * 60 * 5) {
        userStore.refreshToken().then((token) => {
          config.headers.Authorization = token;
          return config;
        });
      }
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { type, msg, success, data } = response.data;
    if (type === 0) {
      if (success) {
        return response.data;
      } else {
        ElMessageBox.alert(msg, "提示", {
          type: "error",
        });
        return;
      }
    }
    if (type === 20) {
      const items = data || [];
      let errorMsg = msg;
      items.forEach((item: any) => {
        errorMsg += "<br/>" + item;
      });
      ElMessage.error({ message: errorMsg, dangerouslyUseHTMLString: true });
      // ElMessageBox.alert(errorMsg, "提示", {
      //   type: "error",
      //   dangerouslyUseHTMLString: true,
      // });
      return;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }
    if (!success) {
      // ElMessageBox.alert(msg, "提示", {
      //   type: "error",
      // });
      ElMessage.error(msg);
      return;
    }

    // ElMessage.error(msg || "系统出错");
    ElMessageBox.alert(msg || "系统出错", "提示", {
      type: "error",
    });
    return Promise.reject(new Error(msg || "Error"));
  },
  (error: any) => {
    const userStore = useUserStore();
    console.log(error);
    const { status } = error.response;

    if (status === 500) {
      ElMessageBox.confirm("服务器异常,请稍后再试!", "提示", {
        confirmButtonText: "确定",
        type: "error",
      }).then(() => {});
    }

    if (status === 403) {
      ElMessageBox.confirm("当前操作没有权限", "提示", {
        confirmButtonText: "确定",
        type: "error",
      }).then(() => {});
    }

    if (status === 401) {
      ElMessageBox.confirm("未登录，请重新登录！", "提示", {
        confirmButtonText: "确定",
        type: "error",
      }).then(() => {
        userStore.logout().then(() => {
          // window.location.replace("/login")
        });
      });
    }

    // if (error.response.data) {
    //   const { type, msg } = error.response.data;
    //   // token 过期,重新登录
    //   if (type === 10 || type===30) {
    //     ElMessageBox.confirm('当前页面已失效，请重新登录', '提示', {
    //       confirmButtonText: '确定',
    //       type: 'warning'
    //     }).then(() => {
    //       localStorage.clear();
    //       window.location.href = '/';
    //     });
    //   } else {
    //     ElMessage.error(msg || '系统出错');
    //   }
    // }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
